﻿var app = angular.module("starter");
app.controller("app.home", [
    "$rootScope", "$scope", "$ionicModal", "$cordovaCamera",
    "$cordovaToast",
    "$cordovaFile",
    "$cordovaGeolocation",
    "$timeout",
    "$window",
    "$q",
    "$tianditu",
    "sky.lyjt.accountService",
    "sky.lyjt.patroService",
    "sky.lyjt.ui",
    function ($rootScope, $scope, $ionicModal, $cordovaCamera, $cordovaToast,
        $cordovaFile, $cordovaGeolocation, $timeout, $window, $q, $tianditu,accountService, patroService,ui) {
        var vm = $scope.vm = {
            date: new Date(),
            imageList: [],
            desc: '',
            lng: 0,
            lat: 0,
            type:"1",
            locationInfo: "",
            refresh: function() {
                var self = this;
                self.desc = '';
                self.lng = 0;
                self.lat = 0;
                self.type = "1";
                self.locationInfo="";
                self.imageList.length = 0;
                self.date = new Date();

                self.location();
            },
            save: function() {
                var self = this;

                ui.showLoading({ text: "正在保存..." });
                patroService.saveImage(self.imageList, {
                    desc: self.desc,
                    lng: self.lng,
                    lat: self.lat,
                    type: self.type,
                    inspectionDate: self.date
                }).then(function(res) {
                    
                    self.refresh();
                    $cordovaToast.showShortBottom("保存成功");

                }).catch(function(err) {
                    console.log(err);
                })
                .finally(function () {
                    ui.hideLoading();
                });

            },
            cancel: function() {
                var self = this;
                self.refresh();
            },
            addImage: function() {
                var self = this;
                var options = {
                    quality: 50,
                    destinationType: Camera.DestinationType.FILE_URI,
                    sourceType: 1, // Camera.PictureSourceType.CAMERA,
                    correctOrientation: true,
                    saveToPhotoAlbum: false
                };

                $cordovaCamera.getPicture(options).then(function (reponse) {
                    console.log(reponse);

                    var cacheFile = reponse; // cordova.file.externalRootDirectory;

                    self.imageList.push(cacheFile);

                    /*var index = cacheFile.substr(-1).indexOf("/");

                    var paths = _.split(cacheFile, '/');
                    var length = paths.length;

                    var fileName = paths[length - 1];
                    console.log('filename:', fileName);

                    var path = cacheFile.substr(0, index + 1);
                    console.log('path:', path);*/

                    //var url = "data:image/jpeg;base64," + reponse;
                    //self.imageList.push(url);

                }, function(err) {
                    
                });
/*
                $cordovaCamera.cleanup().then(function() {
                    
                });*/
                
            },
            location: function () {

                vm.locationInfo = "定位中...";
                $cordovaGeolocation.getCurrentPosition({
                    enableHighAccuracy: true,
                    maximumAge: 30000,
                    timeout: 27000
                }).then(function(position) {

                    vm.lng = position.coords.longitude;
                    vm.lat = position.coords.latitude;
                    vm.locationInfo = "定位成功";
                   
                }).catch(function(err) {
                    
                    vm.lng = -1;
                    vm.lat = -1;
                    vm.locationInfo = "定位失败";
                });
            }
        };
        var loginVm = $scope.loginvm = {
            logo: "img/mike.png",
            username: '',
            password:'',
            login: function() {
                var self = this;

                ui.showLoading({ text: "正在登陆" });
                accountService.login(self.username, self.password)
                    .then(function (res) {
                        
                        var data = res.data;
                        if (!data.success) {
                            $cordovaToast.showShortBottom("登录失败");
                            return;
                        }

                        $cordovaToast.showShortBottom("登录成功");
                        $scope.closeLoginModal();
                        $rootScope.app.userKey = data.result;

                        vm.location();
                    })
                    .finally(function() {
                        ui.hideLoading();
                    });
            }
        };
        
        $ionicModal.fromTemplateUrl("templates/loginModal.html", {
            scope: $scope,
            animation: "slide-in-up",
            backdropClickToClose:false
        }).then(function(modal) {
            $scope.loginModal = modal;
        });


        $scope.openLoginModal = function() {
            $scope.loginModal.show();
        };
        $scope.closeLoginModal = function() {
            $scope.loginModal.hide();
        };

        $scope.$on("$destroy", function() {
            $scope.loginModal.remove();
        });


        $scope.$on("$ionicView.beforeEnter",
            function() {

            });

        $scope.$on("$ionicView.enter",
            function() {

                if ($rootScope.app.userKey==null) {
                    $scope.openLoginModal();
                }

            });


    }
]);